// 路由映射表
const routeMap = {
    home: 'http://localhost:9095/chxt/web/home.html',
    departmentManagement: 'http://localhost:9095/chxt/web/crm/basicArchives/systemUserManagement/departmentManagement.html',
    roleManagement: 'http://localhost:9095/chxt/web/crm/basicArchives/systemUserManagement/roleManagement.html',
    userManagement: 'http://localhost:9095/chxt/web/crm/basicArchives/systemUserManagement/userManagement.html',
    consignorManagement:'http://localhost:9095/chxt/web/crm/basicArchives/ConsignorDossier/consignorManagement.html',
    consignorType:'http://localhost:9095/chxt/web/crm/basicArchives/ConsignorDossier/consignorType.html',
    customerCarBrand:'http://localhost:9095/chxt/web/crm/basicArchives/ConsignorDossier/customerCarBrand.html',
    customerCarModel:'http://localhost:9095/chxt/web/crm/basicArchives/ConsignorDossier/customerCarModel.html',
    highwaySupplier:'http://localhost:9095/chxt/web/crm/basicArchives/supplierDossier/highwaySupplier.html',
    waterwaySupplier:'http://localhost:9095/chxt/web/crm/basicArchives/supplierDossier/waterwaySupplier.html',
    carManager:'http://localhost:9095/chxt/web/crm/basicArchives/supplierDossier/carManager.html',
    shipManager:'http://localhost:9095/chxt/web/crm/basicArchives/supplierDossier/shipManager.html',
    area:'http://localhost:9095/chxt/web/crm/basicArchives/dealerDossier/area.html',
    dealerManagement:'http://localhost:9095/chxt/web/crm/basicArchives/dealerDossier/dealerManagement.html',
    lineManagement:'http://localhost:9095/chxt/web/crm/basicArchives/dealerDossier/lineManagement.html',
    addressManagement:'http://localhost:9095/chxt/web/crm/basicArchives/addressDossier/addressManagement.html',
    transportationPlanning:'http://localhost:9095/chxt/web/crm/logisticsScheduling/planManagement/transportationPlanning.html',
    transportationcv:'http://localhost:9095/chxt/web/crm/logisticsScheduling/planManagement/transportationcv.html',
    vehicleDeployManagement:'http://localhost:9095/chxt/web/crm/logisticsScheduling/fleetManagement/vehicleDeployManagement.html',
    shipDeployManagement:'http://localhost:9095/chxt/web/crm/logisticsScheduling/shipManagement/shipDeployManagement.html',
    deployTracking:'http://localhost:9095/chxt/web/crm/logisticsScheduling/trackingInfo/deployTracking.html',
    revenuePrice:'http://localhost:9095/chxt/web/crm/financeManagement/financePrice/revenuePrice.html',
    spendPrice:'http://localhost:9095/chxt/web/crm/financeManagement/financePrice/spendPrice.html',
    ledgerManagement:'http://localhost:9095/chxt/web/crm/financeManagement/financeledger/ledgerManagement.html',
};

// 动态加载内容函数
// async function loadContent(id) {
//     const targetUrl = routeMap[id];
//
//     if (!targetUrl) {
//         content.innerHTML = `<div class="error">❌ 无效页面标识: ${id}</div>`;
//         return;
//     }
//     // content.innerHTML = '<div class="loading">⏳ 加载中...</div>';
//
//     try {
//         fetch(targetUrl)
//             .then(response => {
//                 if (!response.ok) throw new Error(`HTTP错误 ${response.status}`);
//                 return response.text();
//             })
//             .then(html => {
//                 content.innerHTML = html;
//             })
//             .catch(error => {
//                 content.innerHTML = `<div class="error">❌ 加载失败: ${error.message}</div>`;
//             });
//     }catch (error){
//         // 统一处理错误（网络错误/CORS/解析失败）
//         content.innerHTML = `<div class="error">❌ 加载失败: ${error.message}</div>`;
//     }
// }
const loadedScripts = new Set(); // 全局缓存池
// 修改后的动态加载函数
async function loadContent(id) {
    // try {
        // 清理旧页面资源
        document.querySelectorAll('[data-dynamic-resource]').forEach(el => el.remove());

        const response = await fetch(routeMap[id]);
        if (!response.ok) throw new Error(`HTTP错误 ${response.status}`);
        const html = await response.text();

        // 1. 创建临时容器解析HTML结构
        const parser = new DOMParser();
        const doc = parser.parseFromString(html, 'text/html');

        // 2. 提取CSS资源
        const styles = doc.querySelectorAll('link[rel="stylesheet"]');
        styles.forEach(link => {
            // const newLink = document.createElement('link');
            // newLink.rel = 'stylesheet';
            // newLink.href = link.href;
            // document.head.appendChild(newLink);
            const href = new URL(link.href, routeMap[id]).href;
            if (!loadedResources.has(href)) {
                const newLink = document.createElement('link');
                newLink.rel = 'stylesheet';
                newLink.href = href;
                newLink.dataset.dynamicResource = true; // 标记动态资源[5](@ref)
                document.head.appendChild(newLink);
                loadedResources.add(href);
            }
        });

        // 3. 插入HTML主体内容
        content.innerHTML = doc.body.innerHTML;

        // 4. 动态执行JS脚本
        const scripts = doc.querySelectorAll('script');
        const loadPromises = [];
        scripts.forEach(oldScript => {
            const newScript = document.createElement('script');
            newScript.dataset.dynamicResource = true; // 标记动态资源
            if(oldScript.src) {
                const src = new URL(oldScript.src, routeMap[id]).href;
                if (loadedResources.has(src)) return;

                newScript.src = src;
                loadedResources.add(src);

                // 异步加载控制[7](@ref)
                const loadPromise = new Promise((resolve, reject) => {
                    newScript.onload = resolve;
                    newScript.onerror = reject;
                });
                loadPromises.push(loadPromise);
            } else {
                newScript.textContent = `(function(){ ${oldScript.textContent} })();`; // 作用域隔离[6](@ref)
            }
            document.body.appendChild(newScript);
        });
        // 等待所有外部脚本加载完成
        await Promise.all(loadPromises);
    // } catch (error) {

        // content.innerHTML = `<div class="error">❌ 加载失败: ${error.message}</div>`;
    // }
}

function formatDateTime(input, format = 'YYYY-MM-DD HH:mm:ss') {
    const date = new Date(input);
    if (isNaN(date)) throw new Error('Invalid date input');

    const pad = (num) => num.toString().padStart(2, '0');
    const parts = {
        YYYY: date.getFullYear(),
        MM: pad(date.getMonth() + 1),
        DD: pad(date.getDate()),
        HH: pad(date.getHours()),
        mm: pad(date.getMinutes()),
        ss: pad(date.getSeconds())
    };

    return format.replace(/YYYY|MM|DD|HH|mm|ss/g, (match) => parts[match]);
}

// 统一获取分页参数的方法
function getPaginationParams() {
    return {
        page: Math.max(1, parseInt(document.querySelector('.page-num span').textContent)),
        pageSize: parseInt(document.querySelector('.data-table-page').value)
    }
}

